package com.woniuxy.pxxt.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.pxxt.common.enums.ListFormatStatusEnum;
import com.woniuxy.pxxt.common.enums.UrlStatusEnum;
import com.woniuxy.pxxt.common.result.Result;
import com.woniuxy.pxxt.common.vo.CourseEditVo;
import com.woniuxy.pxxt.common.vo.CourseEttVo;
import com.woniuxy.pxxt.common.vo.SelectTrainVo;
import com.woniuxy.pxxt.common.vo.UserTrainAndCourseMsgVo;
import com.woniuxy.pxxt.dao.*;
import com.woniuxy.pxxt.common.vo.train.SetUserTrainVo;
import com.woniuxy.pxxt.dao.*;
import com.woniuxy.pxxt.dto.*;
import com.woniuxy.pxxt.dto.user.UserTrainAndCourseMsgDtoSkc;
import com.woniuxy.pxxt.entity.ListSource;
import com.woniuxy.pxxt.entity.Role;
import com.woniuxy.pxxt.entity.User;
import com.woniuxy.pxxt.entity.User_Role;
import com.woniuxy.pxxt.service.UserService;
import com.woniuxy.pxxt.utils.QiniuUtil;
import com.woniuxy.pxxt.utils.TokenUtil;
import lombok.val;
import com.woniuxy.pxxt.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLOutput;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <P> @Author: ideaAdmin
 * <P> TODO: Class
 * <P> TODO: 用户表(User)表服务实现类
 * <P> Date: 2022/3/7:13:19
 * <P> Description:
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private TrainDao trainDao;

    @Autowired
    private ListSourceDao listSourceDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserScoreDao userScoreDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private QiniuUtil qiniuUtil;



    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public Result addUserToTrain(SetUserTrainVo setUserTrainVo) {
        userScoreDao.setUserStatusByUidAndTrainId(setUserTrainVo);
        return null;
    }

    @Override
    public Result findUserMsg(Integer userId) {
        UserMsgDtoSkc userMsgDtoSkc = userDao.findUserMsg(userId);

        //设置用户的部门id 和 角色id
        Integer departmentId = userDao.findById(userId).getDepartmentId();

        userMsgDtoSkc.setDepartmentId(departmentId);
        List<Role> allRole = roleDao.findAllRole();
        for (Role role : allRole) {
            if (role.getRole().equals(userMsgDtoSkc.getRole())) {
                userMsgDtoSkc.setRoleId(role.getId());
            }
        }
        //获取用户信息
        //获取用户头像
        ListSource listSource = listSourceDao.findUserListSource(userId, 3);
        if (listSource != null && listSource.getListUrl() != null) {
            userMsgDtoSkc.setUserImg( QiniuUtil.HTTP_PREV +  //前缀
                    qiniuUtil.getFileDomain() + //后缀
                    "/" +
                    listSource.getListUrl());//资源名字


        }
        return Result.ok(userMsgDtoSkc);
    }

    @Override
    public Result findManagerPerson() {
        List<ManagerPersonAllDto> managerPersonAll = userDao.findManagerPerson();
        List<SelectMenuDto> statusDto = trainDao.findStatus();
        Object[] selectedOptions = new Object[2];
        selectedOptions[0] = managerPersonAll;
        selectedOptions[1] = statusDto;
        return Result.ok(selectedOptions);
    }

    @Override
    public Result findUserAllTrain(SelectTrainVo selectTrainVo) {
        if(selectTrainVo != null && selectTrainVo.getUserId() == null){
            selectTrainVo.setUserId(TokenUtil.getUser().getId());
        }
        //获取当前用户的所有培训
        List<UserTrainDtoSkc> userTrainDtoSkcs = trainDao.findUserAllTrain(selectTrainVo);

        if (userTrainDtoSkcs.size() < 1) {
            return Result.ok().message("当前用户没有此类课程");
        }
        userTrainDtoSkcs.forEach(userTrainDtoSkc -> {
            //查找该培训资源的类型
            ListSource listSource = this.packTrainCoverUrl(
                    UrlStatusEnum.IS_TRAIN_URL.getUrlType(),
                    ListFormatStatusEnum.IS_IMG.getUrlType(),
                    userTrainDtoSkc.getId());

            if (listSource != null && listSource.getListUrl() != null) {
                userTrainDtoSkc.setCoverUrl(
                        QiniuUtil.HTTP_PREV +  //前缀
                         qiniuUtil.getFileDomain() + //后缀
                                "/" +
                        listSource.getListUrl());//资源名字
            }
        });
        return Result.ok(userTrainDtoSkcs);
    }

    @Override
    @Transactional
    public Result updateUser(UserMsgDtoSkc userMsgDtoSkc) {
        //先修改用户对象
        int i = userDao.updateUserById(userMsgDtoSkc);

        //更改用户角色表
        roleDao.updateRoleByUserId(userMsgDtoSkc);

        return Result.ok().message("修改成功");
    }

    @Override
    public Result getUserAllMsg(Integer currentPage, Integer pageSize, UserTrainAndCourseMsgVo userTrainAndCourseMsgVo) {
        PageHelper.startPage(currentPage, pageSize);

        List<UserTrainAndCourseMsgDtoSkc> lists = userDao.getUserAllMsg(userTrainAndCourseMsgVo);

        PageInfo<UserTrainAndCourseMsgDtoSkc> of = PageInfo.of(lists);
        return Result.ok(of);
    }

    @Override
    public Result userLogin(User user) {
        String code = (String) redisTemplate.opsForValue().get(user.getCodeToken());

//        if (user.getCode() == null || !code.equals(user.getCode())) {
//            throw  new  RuntimeException("验证码错误");
//        }

        User newUser = userDao.findByAccount(user);

        if (newUser == null) {
            return Result.fail().message("账户不存在");
        }
        if (!newUser.getPassword().equals(user.getPassword())) {
            return Result.fail().message("密码错误");
        }
        String token = JWTUtil.sign(user.getAccount(), user.getPassword());

        newUser.setPassword(null);

        newUser.setToken(token);
        redisTemplate.opsForValue().set(token, newUser);
        redisTemplate.expire(token, 1440, TimeUnit.MINUTES);

        return Result.ok(newUser);
    }

    @Override
    public Result findSomeCourse(CourseEttVo courseEttVo) {
        List<CourseEttVo>courseEttVos = userDao.findSomeCourse(courseEttVo);
        if (courseEttVos.size()<0){
            return Result.fail().message("该用户没有对应课程");
        }else {
            for (int i = 0; i < courseEttVos.size(); i++){
//                System.out.println(courseEttVos.get(i));
                if(courseEttVos.get(i).getCourseStatus() == 0){
                    courseEttVos.get(i).setCourseStatus1("课程未开始");
                }else if(courseEttVos.get(i).getCourseStatus() == 1){
                    courseEttVos.get(i).setCourseStatus1("课程未结束");
                }else if (courseEttVos.get(i).getCourseStatus() == 2){
                    courseEttVos.get(i).setCourseStatus1("课程已结束");
                }
            }
            return Result.ok(courseEttVos) ;
        }

    }

    @Override
    public Result addOne(UserMsgDtoSkc userMsgDtoSkc) {
        int num = userDao.addOne(userMsgDtoSkc);

        if (num > 0) {
            User_Role user_role = new User_Role();
            user_role.setRole_id(userMsgDtoSkc.getRoleId());
            user_role.setUserId(userMsgDtoSkc.getId());
            System.out.println(userMsgDtoSkc.getId());
            int num1 = userDao.addUserRole(user_role);
            if (num1 > 0) {
                return Result.ok().message("添加成功");
            }
        }
        return Result.fail().message("添加失败 稍后再试");
    }

    /**
     * <P>Author ideaAdmin
     * <P>TODO: 返回当前查询的课程对象
     * <P>Date 11:45 2022/3/14
     * <P>* @param courseEditVo
     * <P>* @return courseEditVo
     **/
    @Override
    public Result findAllCourse(Integer userId) {
        List<CourseEditVo> courseEditVoList = userDao.findCourseById(userId);
        if (courseEditVoList.size()<1){
            return Result.fail().message("该用户没有课程");
        }else {
//            courseEditVoList.forEach(courseEditVo -> {
//                System.out.println(courseEditVo.getId());
//                int id=courseEditVo.getId();
//                System.out.println(userDao.findCourse(id).getCourseTitle());
//                courseEditVo = userDao.findCourse(id);
//            });
//            if(courseEditVoList.size() <= 0){
//                return Result.ok().message("当前用户没有课程");
//            }
            for (int i = 0; i< courseEditVoList.size();i++){
                Integer courseStatus = courseEditVoList.get(i).getCourseStatus();
                courseEditVoList.set(i,userDao.findCourse(courseEditVoList.get(i).getId()));
                if(courseStatus == 0){
                    courseEditVoList.get(i).setCourseStatus1("课程未开始");
                }else if(courseStatus == 1 ){
                    courseEditVoList.get(i).setCourseStatus1("课程未结束");
                }else if(courseStatus == 2 ){
                    courseEditVoList.get(i).setCourseStatus1("课程已结束");
                }
//                courseEditVoList.get(i).setCourseStatus(courseStatus);
            }

            return Result.ok(courseEditVoList);
        }
//        List<CourseEditVo> courseEditVoList = userDao.findAllCourseEditVo();

    }


    /**
     * <P>Author ideaAdmin
     * <P>TODO: 返回当前查询的对象的资源 和 资源id
     * <P>Date 11:45 2022/3/10
     * <P>* @param userTrainDtoSkc
     * <P>* @return void
     **/
    private ListSource packTrainCoverUrl(Integer url_status, Integer list_format, Integer id) {
        //通过id 获得对象的url
        ListSource listSource = trainDao.findCoverUrlById(url_status, list_format, id);
        return listSource;
    }
}
